using Microsoft.AspNetCore.Mvc.Filters;
using Vin.Extension.Framework.Signals.ServiceInterface;
using Vin.Tool.AspNetCore.Singleton;
using Vin.Tool.Core.AssertCategory;
using Vin.Tool.Core.NetCategory;
using Vin.Tool.Domain.ExceptionModel;

namespace Vin.Extension.Framework.Signals.Attributes;

public class VinNumberSignalAttribute(string key, string valueField) : Attribute, IAsyncActionFilter
{
    public bool FromBody { get; set; } = false;

    public string NoKeyErrorMessage { get; set; } = "当前信号不存在，请刷新重试！";

    public string IsRepeatErrorMessage { get; set; } = "当前信号已提交，请勿重复提交！";

    public async Task OnActionExecutionAsync(ActionExecutingContext context, ActionExecutionDelegate next)
    {
        var value = context.HttpContext.Request.Query[valueField].ToString();
        if (FromBody)
        {
            var body = await context.HttpContext.ReadToJson();
            if (body?.TryGetProperty(valueField, out var valueJson) == true)
            {
                value = valueJson.GetRawText();
            }
            else
            {
                throw new BusinessException(NoKeyErrorMessage);
            }
        }
        
        if (value.IsNullOrEmpty())
        {
            throw new BusinessException(NoKeyErrorMessage);
        }

        var vinSignalService = VinApp.GetRequiredServiceByHttpContext<IVinSignalService>();
        var count = await vinSignalService.CheckSignalAsync(value, key);
        if (count == 1)
        {
            await vinSignalService.RemoveSignalAsync(value, key);
            throw new BusinessException(NoKeyErrorMessage);
        }

        if (count > 2)
        {
            throw new BusinessException(IsRepeatErrorMessage);
        }

        await vinSignalService.RemoveSignalAsync(value, key);

        await next();
    }
}